//
//  FSAlreadyDoViewController.m
//  WZSOA
//
//  Created by 刘沿 on 16/6/28.
//  Copyright © 2016年 刘沿. All rights reserved.
//

#import "FSAlreadyDoViewController.h"
#import "GDataDefines.h"


@interface FSAlreadyDoViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,assign)int currentPage; //当前页

@property(nonatomic,assign)int totalCounts;


@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic,strong) UITableView *tableView;

@end

@implementation FSAlreadyDoViewController

static NSString * const reuseIdentifier = @"reuseIdentifier";

-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIView *view = [[UIView alloc] init];
    
    view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:view];
    
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).mas_offset(64);
        make.left.equalTo(self.view.mas_left).mas_offset(20);
        make.right.equalTo(self.view.mas_right).mas_offset(-20);
        make.height.equalTo(@40);
    }];
    
//图片
    UIImageView *image = [[UIImageView alloc] init];
    [view addSubview:image];
    [image mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view.mas_top).mas_offset(5);
        make.left.equalTo(view.mas_left).mas_offset(5);
        make.width.equalTo(@30);
        make.bottom.equalTo(view.mas_bottom).mas_offset(-5);
    }];
    
    UILabel *lbl = [[UILabel alloc] init];
    
    [view addSubview:lbl];
    
    [lbl mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(image.mas_right).mas_offset(5);
        
        make.width.equalTo(@200);
        
        make.centerY.equalTo(image);
    }];
    
    if (self.type == alreadySend) {
        //已办发文流转
        image.image = [UIImage imageNamed:@"已办发文（流转中）-2"];
        lbl.text = @"已办发文(流转中)";
        
    }else if(self.type == alreadyReceive){
        //已办收文流转
        image.image = [UIImage imageNamed:@"已办收文（流转中）-2"];
        lbl.text = @"已办收文(流转中)";
    }else if(self.type == alreadyReceiveArchive){
        //已办收文已归档
        image.image = [UIImage imageNamed:@"已办收文（已归档）-2"];
        lbl.text = @"已办收文(已归档)";
        
    }else{
        //已办发文已归档
        image.image = [UIImage imageNamed:@"已办发文（已归档）-2"];
        lbl.text = @"已办发文(已归档)";
    }
    
    
    UITableView *tab = [[UITableView alloc] init];
    tab.delegate = self;
    tab.dataSource = self;
    self.tableView = tab;

    //不设置这个会下移一段距离
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    //不设置这个会下移一段距离
    [self.view addSubview:tab];
    
    [tab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(view.mas_bottom).mas_offset(3);
        
        make.left.equalTo(self.view.mas_left).mas_offset(20);
        
        make.right.equalTo(self.view.mas_right).mas_offset(-20);
        
        make.bottom.equalTo(self.view.mas_bottom).mas_offset(-20);
        
    }];
    
    __weak typeof (self) weakSelf = self;
    // 添加一个头部的刷新控件
    
    [self.tableView addHeaderWithCallback:^{
        
        weakSelf.currentPage = 1;
        
        [weakSelf loadData];
        
    }];
    
    //主动让下拉刷新头部控件进入刷新状态
    [self.tableView headerBeginRefreshing];
    
    //    添加一个尾部的刷新控件
    
    [self.tableView addFooterWithCallback:^{
        
        if ((self.currentPage - 1) * KPageSize < self.totalCounts) {
            
            [weakSelf loadMore];
        }else {
            
            [weakSelf.tableView footerEndRefreshing];
            [weakSelf.view makeToast:@"没有更多了"];
        }
        
    }];
    
    
}
- (void)loadData{
    
    NSString *method = nil;
    
    if (self.type == alreadySend) {
//已办发文流转
        method = KtoybFwPage;
        
    }else if(self.type == alreadyReceive){
//已办收文流转
        method = KtoybSwPage;
    
    }else if(self.type == alreadyReceiveArchive){
//已办收文已归档
    
        method = KtoArchiveSwPage;
        
    }else{
//已办发文已归档
        
        method = KtoArchiveFwPage;
    
    }
    
    NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    
    [HttpTools postWithURL:Kexchrecent arrays:array method:method success:^(id JSON) {
        
        if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
        
        self.dataArray = [self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]];
        
        [self.tableView reloadData];
        
        [self.tableView headerEndRefreshing];
        
        self.currentPage ++;
        
        if (self.dataArray.count == 0) {
            
            [self.view makeToast:@"暂时还没有已办发文哦"];
            
        }
        
    } failure:^(NSError *error) {
        
    }];

}

- (void)loadMore{

    NSString *method = nil;
    
    if (self.type == alreadySend) {
        //已办发文流转
        method = KtoybFwPage;
        
    }else if(self.type == alreadyReceive){
        //已办收文流转
        method = KtoybSwPage;
        
    }else if(self.type == alreadyReceiveArchive){
        //已办收文已归档
        
        method = KtoArchiveSwPage;
        
    }else{
        //已办发文已归档
        
        method = KtoArchiveFwPage;
        
    }
    
    NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    
    [HttpTools postWithURL:Kexchrecent arrays:array method:method success:^(id JSON) {
        
        if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }

        [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];
        
        [self.tableView reloadData];
        
        [self.tableView footerEndRefreshing];
        
        self.currentPage ++;
        
        if (self.dataArray.count == 0) {
            
            [self.view makeToast:@"暂时还没有已办发文哦"];
            
        }
        
    } failure:^(NSError *error) {
        
    }];



}

#pragma mark-----解析服务器返回的二进制数据
-(NSMutableArray*)getDataList:(NSData*)data
{
    NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            FSReceiveModel* model = [[FSReceiveModel alloc] init];
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            GDataXMLElement * timeElement = [[data elementsForName:@"接收时间"] objectAtIndex:0];
            GDataXMLElement * nameElement = [[data elementsForName:@"上一办理人"] objectAtIndex:0];
            GDataXMLElement * stateElement = [[data elementsForName:@"公文状态"] objectAtIndex:0];
            GDataXMLElement * formElement = [[data elementsForName:@"表单"] objectAtIndex:0];
            GDataXMLElement * fileIdElement = [[data elementsForName:@"标识"] objectAtIndex:0];
            model.title = [titleElement stringValue];
            model.time = [timeElement stringValue];
            model.name = [nameElement stringValue];
            model.state = [stateElement stringValue];
            model.form = [formElement stringValue];
            model.fileId = [fileIdElement stringValue];
            [array addObject:model];
        }
    }
    
    //获取根节点下的数据
    NSArray *countArray= [rootElement elementsForName:@"控制"];
    for (GDataXMLElement * data in countArray) {
        GDataXMLElement * countElement = [[data elementsForName:@"条数"] objectAtIndex:0];
        NSString * counts = [countElement stringValue];
        self.totalCounts = [counts intValue];
    }
    if (self.type == alreadySend) {
        //已办发文流转
    self.title = [NSString stringWithFormat:@"已办发文(流转中)(%lu)",(unsigned long)self.totalCounts];
        

    }else if(self.type == alreadyReceive){
        //已办收文流转
    self.title = [NSString stringWithFormat:@"已办收文(流转中)(%lu)",(unsigned long)self.totalCounts];
        

    }else if(self.type == alreadyReceiveArchive){
        //已办收文已归档
    self.title = [NSString stringWithFormat:@"已办收文(已归档)(%lu)",(unsigned long)self.totalCounts];
        

    }else{
        //已办发文已归档
    self.title = [NSString stringWithFormat:@"已办发文(已归档)(%lu)",(unsigned long)self.totalCounts];

    }

       return array;
}

#pragma mark-------数据源和代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    FSAlreadyDoCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (cell == nil) {
        
        cell = [FSAlreadyDoCell alreadyDoCell];
    }
    cell.receiveModel = self.dataArray[indexPath.row];
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    FSReceiveModel *model = self.dataArray[indexPath.row];
    
    CGFloat titleFloat = [FSHightTool heightbyString:model.title font:15 minsWidth:60];
    NSString *desstring = [NSString stringWithFormat:@"%@/%@/%@",model.time,model.state,model.name];
    
    CGFloat desfloat = [FSHightTool heightbyString:desstring font:15 minsWidth:60];
    
    return titleFloat + desfloat + 30;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    
    FSReceiveModel *model = self.dataArray[indexPath.row];
    
    FSAlreadyDetailController *alDetail = [sb instantiateViewControllerWithIdentifier:@"AlreadyDetailVC"];
    alDetail.field = model.fileId;
    
    alDetail.type2 = self.type;
    
    [self.navigationController pushViewController:alDetail animated:YES];
    
}





@end














